package com.sgb.goods.view.fragment.manage;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;

import com.blankj.utilcode.util.KeyboardUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.goods.BR;
import com.sgb.goods.R;
import com.sgb.goods.databinding.GoodsFragmentManageListLeftBinding;
import com.sgb.goods.entity.DictEntity;
import com.sgb.goods.entity.GoodsManageListEntity;
import com.sgb.goods.entity.MenuEntity1;
import com.sgb.goods.utils.Constants;
import com.sgb.goods.utils.SmartUtils;
import com.sgb.goods.utils.StringUtils;
import com.sgb.goods.utils.base.fragment.BaseFragment;
import com.sgb.goods.utils.helper.SmartRefreshLayoutHelper;
import com.sgb.goods.view.adapter.publish.pop.GoodsTypePopWindow;
import com.sgb.goods.viewmodel.GoodsManageListLeftViewModel;
import com.sgb.goods.viewmodel.GoodsManageListViewModel;
import com.sgb.goods.widget.DialogHelper;
import com.sgb.goods.widget.pop.GoodsItemSelect1PopWindow;
import com.swgk.core.util.MToast;

import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * 商品管理-商品管理列表界面(页面一)
 * @author cyj
 */
public class GoodsManageListLeftFragment extends BaseFragment<GoodsFragmentManageListLeftBinding, GoodsManageListLeftViewModel>
        implements SmartRefreshLayoutHelper {

    private GoodsTypePopWindow goodsTypePopWindow;
    private GoodsItemSelect1PopWindow goodsItemSelect1PopWindow;
    private GoodsManageListViewModel mViewModel2;

    @Override
    protected int getLayoutResId() {
        return R.layout.goods_fragment_manage_list_left;
    }

    @Override
    protected void initViewModel() {
        mViewModel = createViewModel(GoodsManageListLeftViewModel.class, BR.viewModel);
        mViewModel2 = createParentViewModel(GoodsManageListViewModel.class);
    }

    @Override
    public void lazyLoadData() {
        mViewModel.getGoodsList(false);
    }

    @Override
    protected void initObserve() {

        mViewModel.goodsList.observe(this, goodsList -> {
            refreshUi(mDataBinding.rlvLayout.refreshLayout, mViewModel.adapter, goodsList);
        });

        // 解决 activity 软件盘收起时搜索内容未更新问题
        mViewModel2.bindSearchContent.observe(this, bindSearchContent -> {
            if(!bindSearchContent.equals(mViewModel2.searchContent.getValue())) {
                mViewModel.condition.set(bindSearchContent);
            }
        });
        // activity 页面内容变更回调通知与处理
        mViewModel2.searchContent.observe(this, searchContent -> {
            // 为所有显示与未显示的 fragment 页面进行搜索内容变量覆盖
            mViewModel.condition.set(searchContent);
            // 当前 fragment 显示，则调用网络请求带搜索内容的数据
            if(Lifecycle.Event.ON_RESUME == currentLifecycleEvent) {
                mViewModel.getGoodsList(false);
            }
        });

        mViewModel.dictEntityList.observe(this, this::showGoodsItemSelect1PopWindow);
        mViewModel.goodsTypeList.observe(this, this::showGoodsTypePopWindow);
    }

    @Override
    protected void initListener() {

        // 发布商品
        mDataBinding.addLayout.setOnClickListener(v -> {
            MToast.showToast(getActivity(), "发布商品暂未实现");
        });

        // 查询商品状态列表
        mDataBinding.allLayout.setOnClickListener(v -> {
            mViewModel.isOpenGoodsStatus.set(true);
            mViewModel.goodsStatusCategory();
        });

        // 查询商品类型列表
        mDataBinding.typeLayout.setOnClickListener(v -> {
            mViewModel.isOpenGoodsType.set(true);
            mViewModel.getGoodsCategory();
        });

        // 商品管理列表更新
        mDataBinding.rlvLayout.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                mViewModel.getGoodsList(true);
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                mViewModel.getGoodsList(false);
            }
        });

        // 商品操作相关点击事件监听
        mViewModel.adapter.setOnItemChildClickListener((adapter, view, position) -> {
            GoodsManageListEntity entity = mViewModel.adapter.getData().get(position);
            int viewId = view.getId();
            if(viewId == R.id.edit_view) {
                // 编辑
                MToast.showToast(getActivity(), "编辑");
            } else if(viewId == R.id.up_view) {
                // 上架
                checkGoodsProperties(Constants.GOODS_OPT_UP, entity.id);
            } else if(viewId == R.id.down_view) {
                // 下架
                checkGoodsProperties(Constants.GOODS_OPT_DOWN, entity.id);
            } else if(viewId == R.id.del_view) {
                // 删除
                checkGoodsProperties(Constants.GOODS_OPT_DEL, entity.id);
            }
        });
    }

    /**
     * 检查商品属性以及弹窗提示
     * @param operation    操作类型
     */
    private void checkGoodsProperties(String operation, String id) {
        if(StringUtils.isEmpty(id)) {
            return;
        }
        if(Constants.GOODS_OPT_UP.equals(operation)) {
            String msg = "商品上架后，则可进行下单购\n买，确认要上架吗？";
            DialogHelper.showDialog(getActivity(), "温馨提示", msg, "确定",
                    new DialogHelper.DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            // 上架
                            mViewModel.upOrDownOrDeleteGoods(Constants.GOODS_OPT_UP, id);
                        }
                    });
        } else if(Constants.GOODS_OPT_DOWN.equals(operation)) {
            String msg = "商品下架后，则无法进行购\n买，确认下架吗？";
            DialogHelper.showDialog(getActivity(), "温馨提示", msg, "确定",
                    new DialogHelper.DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            // 下架
                            mViewModel.upOrDownOrDeleteGoods(Constants.GOODS_OPT_DOWN, id);
                        }
                    });
        } else if(Constants.GOODS_OPT_DEL.equals(operation)) {
            String msg = "删除后不可恢复，请谨慎操作";
            DialogHelper.showDialog(getActivity(), "温馨提示", msg, "确定",
                    new DialogHelper.DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            // 删除
                            mViewModel.upOrDownOrDeleteGoods(Constants.GOODS_OPT_DEL, id);
                        }
                    });
        }
    }

    /**
     * 选择商品分类弹窗
     */
    public void showGoodsTypePopWindow(List<MenuEntity1<MenuEntity1<MenuEntity1>>> menuEntityList) {
        if (null == goodsTypePopWindow) {
            goodsTypePopWindow = new GoodsTypePopWindow(getActivity());
            goodsTypePopWindow.setOnDismissListener(() -> {
                mViewModel.cid3.set(mViewModel.cid3.get());
                mViewModel.isOpenGoodsType.set(false);
            });
            goodsTypePopWindow.setOnResultClick((key1, key2, key3) -> {
                mViewModel.cid3.set(key3 != null ? ((MenuEntity1) key3).id : "");
                mViewModel.getGoodsList(false);
            });
        }
        KeyboardUtils.hideSoftInput(requireActivity().getWindow());
        goodsTypePopWindow.setData(menuEntityList, true);
        goodsTypePopWindow.showAsDropDown(mDataBinding.llBoot);
    }

    /**
     * 选择商品状态弹窗
     */
    public void showGoodsItemSelect1PopWindow(List<DictEntity> list) {
        if (null == goodsItemSelect1PopWindow) {
            goodsItemSelect1PopWindow = new GoodsItemSelect1PopWindow(getActivity());
            goodsItemSelect1PopWindow.setOnDismissListener(() -> {
                mViewModel.status.set(mViewModel.status.get());
                mViewModel.isOpenGoodsStatus.set(false);
            });
            goodsItemSelect1PopWindow.setOnResultClick((key1, key2, key3) -> {
                mViewModel.status.set(key1 != null ? ((DictEntity) key1).id : "");
                mViewModel.getGoodsList(false);
            });
        }
        KeyboardUtils.hideSoftInput(requireActivity().getWindow());
        goodsItemSelect1PopWindow.setData(list);
        goodsItemSelect1PopWindow.showAsDropDown(mDataBinding.line, 0, SmartUtils.getHeight0_5DpToPx());
    }
}